<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/all.conf.php');
require_once(__PHY_WEB.__DIR_ADM.'/admin.inc.php');

$rReq = validate($_REQUEST, 'action:u|id:n|user_ename:u|user_cname:u|new_pswd:u|rep_pswd:u|grantable:i|msg:u');
$sMsg = '';
$sAction = (in_array($rReq['action'], array('list', 'edit', 'new', 'add', 'update', 'grant')) ? $rReq['action'] : 'list');
if (!(0 < $_ME->get('grantable'))) {
	$sMsg .= '你没有管理下属的权限';
	$sAction = 'list';
}

if ('add' == $sAction) {
	$oUser = new aUser();
	$oUser->set('user_ename', $rReq['user_ename']);
	$oUser->set('user_cname', $rReq['user_cname']);
	$oUser->set('parent_id', $_SESSION['ADM_USER_ID']);
	$oUser->set('pswd', md5($rReq['new_pswd']));
	$oUser->set('grantable', ($rReq['grantable'] ? 1 : 0));
	$oUser->set('add_time', date('Y-m-d H:i:s'));
	if (!$rReq['new_pswd']) {
		$sMsg .= '密码不能为空';
	}
	elseif ($rReq['rep_pswd'] != $rReq['new_pswd']) {
		$sMsg .= "两次密码不同".$_br;
	}
	elseif ($s = $oUser->invalid()) {
		$sMsg .= "数据不规范: {$s}".$_br;
	}
	elseif ($oUser->insert()) {
		$sMsg .= '添加成功.'.$_br;
	}
	else {
		$sMsg .= '添加失败'.$_br;
	}
	$sAction = 'list';
}
if ('update' == $sAction) {
	$oUser = new aUser($rReq['id']);
	$oUser->set('grantable', $rReq['grantable']);
	if ($s = $oUser->invalid()) {
		$sMsg .= "数据不规范: {$s}".$_br;
	}
	elseif ($oUser->update()) {
		$sMsg .= '修改成功.'.$_br;
	}
	else {
		$sMsg .= '修改失败'.$_br;
	}
	$sAction = 'list';
}
if ('grant' == $sAction) {
	if ($rParm = validate($_REQUEST, 'id:N|grantto:N')) {
		$oUser = new aUser($rParm['id']);
		$oUser->set('parent_id', $rParm['grantto']);
		if ($s = $oUser->invalid()) {
			$sMsg .= "数据不规范: {$s}".$_br;
		}
		elseif ($oUser->update()) {
			$sMsg .= '修改成功.'.$_br;
		}
		else {
			$sMsg .= '修改失败'.$_br;
		}
	}
	else {
		$sMsg .= '参数错误'.$_br;
	}
	$sAction = 'list';
}
if ('edit' == $sAction) {
	/// 该用户 ///
	$oUser = new aUser($rReq['id']);
	$oTpl->assign('rUser', $oUser->getData());
	/// 我的上级 ///
	$oUpUser = new aUser($_ME->get('parent_id'));
	$oTpl->assign('rUpUser', $oUpUser->getData());
	/// 我的下级组长 ///
	$oGtUserList = new aUserList();
	$oGtUserList->cfgWhere("parent_id='{$_SESSION['ADM_USER_ID']}' AND grantable>0");
	$oGtUserList->cfgOrder("id DESC");
	$oGtUserList->load();
	$oTpl->assign('rGtUser', $oGtUserList->fetchArray());
}
if ('list' == $sAction) {
	$oAdmUserList = new aUserList();
	$oAdmUserList->cfgWhere("parent_id='{$_SESSION['ADM_USER_ID']}'");
	$oAdmUserList->cfgOrder("id DESC");
	$oAdmUserList->load();
	$oTpl->assign('rUsers', $oAdmUserList->fetchArray());
}

$oTpl->assign('sMsg', $sMsg);
$oTpl->assign('sAction', $sAction);
$oTpl->display(dirname(__FILE__).'/'.basename(__FILE__, '.php').'.tpl');
?>
